package com.chen.controller;

import com.alibaba.fastjson.JSON;
import com.chen.pojo.MedicalAssay;
import com.chen.service.DetailServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
@CrossOrigin
@RequestMapping("/detail")
public class DetailController {
    @Resource
    private DetailServiceImpl detailService;
    @Resource
    private RedisTemplate redisTemplate;

    @RequestMapping("/hello")
    public String queryAll(Model model){
        List<MedicalAssay> medicalAssay= detailService.queryAll();
        model.addAttribute("list",medicalAssay);
        return "medical";
    }

    @RequestMapping("/update/{id}")
    public String update(MedicalAssay medicalAssay){
        medicalAssay.setAssay_result(1);
        medicalAssay.setAssay_time(Date.from(Instant.now()));
        detailService.update(medicalAssay);
        return "redirect:/detail/hello";
    }

    @RequestMapping("/find")
    public String queryAllById(Model model, String name){
        String key="medicalAssay_"+name;
        ValueOperations<String,List<MedicalAssay>> operations=redisTemplate.opsForValue();
        boolean haskey= redisTemplate.hasKey(key);
        if (haskey){
            List<MedicalAssay> medicalAssay=operations.get(key);
            System.out.println("从缓存中取数据"+medicalAssay);
            System.out.println("---------------------------------");
            model.addAttribute("list",medicalAssay);
            model.addAttribute("back",name);
            return "medical";
        }else {
            List<MedicalAssay> medicalAssay=detailService.queryAllById(name);
            System.out.println("从数据库中取数据"+medicalAssay);
            System.out.println("---------------------------------");
            model.addAttribute("list",medicalAssay);
            model.addAttribute("back",name);
            operations.set(key, medicalAssay,5,TimeUnit.HOURS);
            return "medical";
        }
    }

    @RequestMapping("/toAdd")
    public String add(){
        return "insert";
    }
    @RequestMapping("/insert")
    public String insert(MedicalAssay medicalAssay){
        medicalAssay.setAssay_result(0);
        if (detailService.add(medicalAssay)>0)
        {
            return "redirect:/detail/1";
        }else {
            return "redirect:/detail/toAdd";
        }
    }
}
